package com.test30_IO流;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 管道流，为了不同进程之间的通讯提供服务
 * 字节流：PipedInputStream、PipedOutputStream
 * 字符流：PipedReader、PipedWriter
 */
public class Demo10_PipedInputStream {

    /**
     * 通过线程管道流实现内容的发送与接收
     */
    public static void main(String[] args) throws Exception {
        SendThread send = new SendThread();
        ReceiveThread receive = new ReceiveThread();
        send.getOutput().connect(receive.getInput());   // 管道连接
        new Thread(send).start();
        new Thread(receive).start();
    }
}

class SendThread implements Runnable {
    private PipedOutputStream output = new PipedOutputStream(); // 管道输出流

    @Override
    public void run() {
        try {   // 通过管道实现数据的发送
            this.output.write("李兴华编程训练营：yootk.ke.qq.com".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public PipedOutputStream getOutput() {  // 通过子类操作
        return this.output;
    }
}

class ReceiveThread implements Runnable {
    private PipedInputStream input = new PipedInputStream();    // 管道输入流

    @Override
    public void run() {
        try {   // 通过管道实现数据的接收
            byte[] data = new byte[1024];
            int len = this.input.read(data);
            System.out.print("【接收到消息】" + new String(data, 0, len));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public PipedInputStream getInput() {    // 通过子类操作
        return this.input;
    }
}
